﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AcctrueWMS.Foundation.Data;
using AcctrueWMS.Foundation.Render;
using System.IO;
using AcctrueWMS.Foundation.Web;
using System.Web.Script.Services;
using System.Text;
using System.Data;
using AcctrueWMS.Foundation.Common;
using AcctrueWMS.Foundation.Util;
using System.Text.RegularExpressions;
using System.Collections;
using AcctrueWMS.Foundation.Web.Session;

namespace AcctrueWMS.Web.Service
{
    /// <summary>
    /// CommonService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    [System.Web.Script.Services.ScriptService]
    public class CommonService : System.Web.Services.WebService
    {
        /// <summary>
        /// 测试方法
        /// By hkl
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World!";
        }

        /// <summary>
        /// 测试WebService连接方法
        /// hkl
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public string TestConnection()
        {
            string result = "";
            try
            {
                result = ExecCmd("wmsql(SELECT HOST_ID() AS hostid,HOST_NAME() AS hostname,DB_ID() AS dbid,DB_NAME() AS dbname)");
            }
            catch
            {
                result = "";
            }
            return result;
        }

        private IDataModelContext context = Runtime.Context;

        public CommonService()
        {
            context = Runtime.Context;

        }
        /// <summary>
        /// 填充DataModel,如果是新增,则将流水号赋值
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="opttype"></param>
        /// <param name="condition"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        private DataModel FillDataModel(string ID, OptTypeEnum opttype, string condition, DataModel model)
        {
            switch (opttype)
            {
                case OptTypeEnum.Modify:
                case OptTypeEnum.View:
                    string QueryStr = PrimaryKeyConBuilder.BuildPrimaryKeyCon(ID, model);
                    if (condition.Trim().Length > 0)
                    {
                        QueryStr += " and " + condition;
                    }
                    model = context.Single(model, QueryStr);
                    break;
                case OptTypeEnum.Add:
                    DataModel modelRow = model.NewRow();
                    ///为生成流水号的列生成流水号
                    foreach (DataModelColumn column in modelRow.Columns)
                    {
                        if (column.SequenceNoGenType.Length != 0)
                        {
                            modelRow[column.Name].Value = column.GenerateSequenceNo();
                        }
                    }
                    model.Rows.Add(modelRow);
                    ///如果有兄弟Model,则增加一行
                    foreach (DataModel brotherModel in model.Brothers)
                    {
                        if (brotherModel.Rows.Count == 0)
                        {
                            DataModel brotherRow = brotherModel.NewRow();
                            brotherModel.Rows.Add(brotherRow);
                        }
                    }
                    break;
                default:
                    break;
            }
            return model;
        }
        /// <summary>
        /// 操作类型
        /// </summary>
        /// <param name="opttype"></param>
        /// <returns></returns>
        private int GetOptType(OptTypeEnum opttype)
        {
            switch (opttype)
            {
                case OptTypeEnum.List:
                case OptTypeEnum.View:
                default:
                    return 0;
                case OptTypeEnum.Add:
                case OptTypeEnum.Modify:
                    return 1;
            }
        }

        /// <summary>
        /// 根据输入的字符过滤结果，并返回，用于FocusedTextBox
        /// </summary>

        /// <param name="startWith">输入字符</param>
        /// <param name="limit">限制条数</param>
        /// <param name="dataExpr">数据命令</param>
        /// <returns></returns>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public List<FocustedTextBoxItem> AutoComplete(string startWith, int limit, string dataExpr)
        {
            startWith = DataHelper.FilterDbExpression(startWith);
            bool supportPy = true;
            dataExpr = HttpUtility.UrlDecode(dataExpr);
            //在含有startWith参数时，无法使用拼音选择。拼音查询只适应于数据量较小情况，一般需小于2000条。
            if (dataExpr.IndexOf("{value}") > 0)
            {
                dataExpr = dataExpr.Replace("{value}", startWith);
                //supportPy = false;
            }
            DataTable dt = CommandExprFactory.Eval(dataExpr, Runtime.Context) as DataTable;

            IEnumerable<DataRow> result = null;
            //根据key值过滤
            DataRow[] keyRows = dt.Select(string.Format("key like '{0}%'", startWith),"key desc");
            //根据value值过滤
            DataRow[] valueRows = dt.Select(string.Format("value like '{0}%'", startWith), "key desc");

            result = keyRows.Union(valueRows);
            //如果支持拼音
            if (supportPy)
            {
                dt.Columns.Add("pinyin", typeof(string));
                foreach (DataRow row in dt.Rows)
                {
                    row["pinyin"] = PinyinFetcher.GetAbbreviation(row["value"].ToString());
                }
                //根据首字符过滤
                DataRow[] pinyinRows = dt.Select(string.Format("pinyin like '{0}%'", startWith));
                result = result.Union(pinyinRows);
            }

            result = result.Distinct();

            List<FocustedTextBoxItem> items = new List<FocustedTextBoxItem>();
            int rowCount = 0;
            foreach (DataRow row in result)
            {
                if (rowCount++ >= limit)
                    break;
                items.Add(new FocustedTextBoxItem() { Key = row["key"].ToString(), Value = row["value"].ToString() });
            }
            return items;
        }

        public class FocustedTextBoxItem
        {
            public string Key
            {
                get;
                set;
            }
            public string Value
            {
                get;
                set;
            }
        }

        /// <summary>
        /// 通过前台传来的表单信息，得到查询条件
        /// </summary>
        /// <param name="modelName"></param>
        /// <param name="expr"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetQueryCond(string modelName, string expr)
        {
            if (System.Web.HttpContext.Current.Session[SessionConst.UserNo] == null)
                return "timeOut";//session超时
            else
                return Runtime.Context.GetQueryCondition(modelName, expr,true);//现在模糊查询
        }

        /// <summary>
        /// 执行数据获取命令
        /// </summary>
        /// <param name="expr"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string ExecCommand(string expr)
        {
            if (System.Web.HttpContext.Current.Session[SessionConst.UserNo] == null)
            {
                return "timeOut";//session超时
            }
            else
            {
                object result = CommandExprFactory.Eval(expr, Runtime.Context);
                if (result is DataTable)
                    return JsonTableConverter.SerializeObject(result as DataTable);
                else if (result is string)
                    return result.ToString();
                else if (result != null)
                    return result.ToString();
                else return string.Empty;
            }
        }

        /// <summary>
        /// 执行数据获取命令
        /// </summary>
        /// <param name="expr"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string ExecCmd(string expr)
        {
            object result = CommandExprFactory.Eval(expr, Runtime.Context);
            if (result is DataTable)
                return JsonTableConverter.SerializeObject(result as DataTable);
            else if (result is string)
                return result.ToString();
            else if (result != null)
                return result.ToString();
            else return string.Empty;
        }
        [WebMethod(EnableSession = true)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public object GetStoreValue(string storeType, string key)
        {
            switch (storeType)
            {
                case "session":
                    if (HttpContext.Current.Session[key] != null)
                        return HttpContext.Current.Session[key].ToString();
                    else
                        return string.Empty;
                case "cache":
                    if (HttpContext.Current.Cache[key] != null)
                        return HttpContext.Current.Cache[key].ToString();
                    else
                        return string.Empty;
            }
            return string.Empty;
        }

        //获取config 配置信息
        [WebMethod(EnableSession = true)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetConfig(string conf)
        {
            return System.Configuration.ConfigurationManager.AppSettings[conf].ToString();
        }
    }

}
